<!-- app获取 openid 授权页面 -->
<template>
  <view class="container">
    <cu-custom :bgColor="'bg-' + theme.backgroundColor" :isBack="false">
      <!-- <block slot="backText">返回</block> -->
      <block slot="content">更新用户</block>
    </cu-custom>
    <!-- 数据编辑展示 -->
    <view v-if="isDebug" class="form-container">
      <view class="form-item">
        <text class="label">token:</text>
        {{ token }}
      </view>

      <view class="form-item">
        <text class="label">openId:</text>
        {{ userInfo.openId }}
      </view>
      <view class="form-item">
        <text class="label">nickName:</text>
        {{ userInfo.nickName }}
      </view>
      <view class="form-item">
        <text class="label">avatarUrl:</text>
        {{ userInfo.headimgUrl }}
      </view>
    </view>

    <view v-if="loding" style="text-align: center; line-height: 300rpx">
      <text>加载中...</text>
    </view>
    <!-- 手动关闭 -->
    <view v-if="successLoding" class="success-container">
      <view class="success-icon">✓</view>
      <view class="success-text">绑定用户成功!</view>
      <button class="exit-button" @click="exitMiniProgram">关闭页面</button>
    </view>
  </view>
</template>

<script>
const app = getApp();
import appApi from "utils/AppApi";
export default {
  data() {
    return {
      theme: app.globalData.theme,
      // 调试
      isDebug: false,
      token: null,
      code: null,
      loding: false,
      // 成功
      successLoding: false,
      userInfo: {},
    };
  },

  onLoad(options) {
    this.userInfo = uni.getStorageSync("user_info") || {};
    // console.log("this.userInfo", JSON.stringify(this.userInfo));
    // console.log("options", options);
    if (options.token) {
      this.isDebug = options.isDebug || false;
      this.token = options.token ? this.base64Decode(options.token) : null;
      // this.token = options.token;
      // 更新用户详情
      this.updateInfo();
    } else {
      uni.showToast({
        title: "缺少token参数",
        icon: "none",
      });
    }
  },

  methods: {
    // base64 解码token方法
    base64Decode(str) {
      try {
        // 使用 uni.base64ToArrayBuffer 进行解码（如果可用）
        if (uni.base64ToArrayBuffer) {
          // 先转换为 ArrayBuffer，再转换为字符串
          const arrayBuffer = uni.base64ToArrayBuffer(str);
          return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        } else {
          // 使用 JavaScript 原生方法进行 base64 解码
          return decodeURIComponent(
            atob(str)
              .split("")
              .map(function (c) {
                return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
              })
              .join("")
          );
        }
      } catch (error) {
        console.error("Base64 解码失败:", error);
        // 如果解码失败，返回原始值
        return str;
      }
    },

    // 更新用户详情
    async updateInfo() {
      if (!this.token) return;
      this.loding = true;
      try {
        const headers = {
          Authorization: `${this.token}`,
          accept: "application/json",
        };
        // 请求后端更新用户详情
        const res = await appApi.customerInfo(
          {
            wechat_openid: this.userInfo.openId,
            wechat_nickname: this.userInfo.nickName || "",
            avatar_url: this.userInfo.headimgUrl || "",
            //"wechat_name": "aaaa",
            // wechat_unionid":Maaaa",
          },
          headers
        );
        this.loding = false;
        if (res.code == 200001) {
          // 成功后显示提示界面，等待用户点击退出
          this.showSuccess();
        }
      } catch (error) {
        this.loding = false;
        let msg = error.message || "更新用户详情失败";
        uni.showToast({
          title: msg,
          icon: "none",
        });
      }
    },

    // 成功后显示提示界面
    showSuccess() {
      this.successLoding = true;
      this.loding = false;
      uni.showToast({
        title: "更新成功",
        icon: "success",
      });
    },

    // 用户点击退出小程序
    exitMiniProgram() {
      if (uni.exitMiniProgram) {
        uni.exitMiniProgram({
          success: function () {
            console.log("成功退出小程序");
          },
          fail: function (err) {
            console.log("退出小程序失败", err);
            uni.showToast({
              title: "请手动返回",
              icon: "none",
            });
          },
        });
      } else {
        uni.showToast({
          title: "当前环境不支持退出小程序",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  // padding: 20rpx;
  .order-info {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }
  .pay-button {
    margin-top: 40rpx;
    background-color: #07c160;
    color: white;
    border: none;
    padding: 20rpx;
    border-radius: 10rpx;
  }
}

.success-container {
  text-align: center;
  padding: 100rpx 40rpx;

  .success-icon {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #07c160;
    color: white;
    font-size: 60rpx;
    line-height: 120rpx;
    margin: 0 auto 40rpx;
  }

  .success-text {
    font-size: 36rpx;
    color: #333;
    margin-bottom: 60rpx;
  }

  .exit-button {
    background-color: #07c160;
    color: white;
    border: none;
    padding: 20rpx 40rpx;
    border-radius: 10rpx;
    font-size: 32rpx;
  }
}

.form-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 60rpx 30rpx;
  margin-bottom: 30rpx;

  .form-item {
    margin-bottom: 25rpx;
    display: flex;
    flex-direction: column;
  }

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
  }

  .input {
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    padding: 30rpx 20rpx;
    font-size: 28rpx;
    height: 100rpx;
    line-height: 70rpx;
    box-sizing: border-box;
  }
}
</style>
